package service

import (
	"server/internal/model"
)

func (svc *Service) NewResource(name, chainName, username, chainAccount, data string, price int) error {
	r := &model.Resource{
		Name:         name,
		ChainName:    chainName,
		Username:     username,
		ChainAccount: chainAccount,
		Price:        price,
		Data:         data,
	}

	return r.Create(svc.engine)
}

func (svc *Service) GetMyResources(username string) ([]map[string]interface{}, error) {
	r := &model.Resource{
		Username: username,
	}
	resources, err := r.GetMy(svc.engine)
	if err != nil {
		return nil, err
	}

	len := len(resources)
	resourceArr := make([]map[string]interface{}, len)
	for i := 0; i < len; i++ {
		resourceArr[i] = make(map[string]interface{})
		resourceArr[i]["id"] = resources[i].ID
		resourceArr[i]["name"] = resources[i].Name
		resourceArr[i]["chainName"] = resources[i].ChainName
		resourceArr[i]["username"] = resources[i].Username
		resourceArr[i]["chainAccount"] = resources[i].ChainAccount
		resourceArr[i]["price"] = resources[i].Price
		resourceArr[i]["data"] = resources[i].Data
	}

	return resourceArr, nil
}

func (svc *Service) GetOnSaleResources() ([]map[string]interface{}, error) {
	r := &model.Resource{}
	resources, err := r.GetOnSale(svc.engine)
	if err != nil {
		return nil, err
	}

	len := len(resources)
	resourceArr := make([]map[string]interface{}, len)
	for i := 0; i < len; i++ {
		resourceArr[i] = make(map[string]interface{})
		resourceArr[i]["id"] = resources[i].ID
		resourceArr[i]["name"] = resources[i].Name
		resourceArr[i]["chainName"] = resources[i].ChainName
		resourceArr[i]["username"] = resources[i].Username
		resourceArr[i]["chainAccount"] = resources[i].ChainAccount
		resourceArr[i]["price"] = resources[i].Price
		resourceArr[i]["data"] = resources[i].Data
	}

	return resourceArr, nil
}

func (svc *Service) DeleteResource(id int) error {
	r := &model.Resource{}
	return r.Delete(svc.engine, id)
}

func (svc *Service) StartSale(id int) error {
	r := &model.Resource{}
	change := make(map[string]interface{})
	change["on_sale"] = 1
	return r.Update(svc.engine, id, change)
}

func (svc *Service) EndSale(id int) error {
	r := &model.Resource{}
	change := make(map[string]interface{})
	change["on_sale"] = 0
	return r.Update(svc.engine, id, change)
}
